import {NavigationFailure, NavigationGuardNext, RouteLocationNormalized, Router} from "vue-router";
import {isEmpty} from "@utils";
import store from "@/store";
import storage from "@/store/storage";

export default {
  whiteList: ['/login'],
  hooks(router: Router) {
    router.beforeEach((to,
                       from, next) =>
      this.beforeEach(to, from, next))
    router.afterEach((to, from,
                      failure) =>
      this.afterEach(to, from, failure))
  },

  beforeEach(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): void {
    if (this.isInWhiteList(to.path)) {
      //在白名单内, 直接跳转即可
      this.toNext(next, from, to);
      return
    }
    //检查一下本地缓存， 如果有缓存的话，那就直接跳转
    //如果没有缓存，那就先加载缓存里面的数据
    //然后再正常跳转即可
    this.checkPermisstion(next, from, to)
  },
  isInWhiteList(path: string): boolean {
    return this.whiteList.includes(path);
  },
  storeHasToken() {
    return !isEmpty(store.getters.token) && !isEmpty(store.getters.userInfo);
  },
  storageHasToken() {
    return !isEmpty(storage.getToken()) && !isEmpty(storage.getUserInfo());
  },
  loadTokenToStore() {
    store.commit('user/setToken', storage.getToken());
    store.commit('user/setUserInfo', storage.getUserInfo());
  },
  toNext(next: NavigationGuardNext, from: RouteLocationNormalized, to: RouteLocationNormalized) {
    if (to.name === 'login') {
      //在已经有了token的情况下，如果还进入登录页面，那就直接再次进入首页
      if (this.storageHasToken()) {
        if (!this.storeHasToken()) {
          this.loadTokenToStore();
        }
        next({name: 'home'});
      } else {
        next();
      }
    } else {
      next();
    }
  },
  checkPermisstion(next: NavigationGuardNext, from: RouteLocationNormalized, to: RouteLocationNormalized) {
    if (this.storeHasToken()) {
      //token不是空的
      this.saveToken();
      this.toNext(next, from, to);
    } else {
      //token是空的
      if (this.storageHasToken()) {
        //有可能是做了一次页面的刷新
        this.loadTokenToStore();
        this.toNext(next, from, to);
      } else {
        //有可能是没有登录
        this.toLogin(next);
      }
    }
  },
  saveToken(): void {
    storage.setToken(store.getters.token);
    storage.setUserInfo(store.getters.userInfo);
  },
  toLogin(next: NavigationGuardNext) {
    next({name: 'login'})
  },
  afterEach(to: RouteLocationNormalized,
            from: RouteLocationNormalized,
            failure: NavigationFailure | void | undefined) {
    this.tryLoadAppDatas()
  },
  tryLoadAppDatas(): void {
    let appData = storage.getAppData();
    if (!isEmpty(appData)) {
      store.commit('app/setAppData', appData);
    }
  }
}
